//
//  CusAnnotationView.m
//  leo
//
//  Created by 张旭 on 15/10/20.
//  Copyright © 2015年 mdx. All rights reserved.
//

#import "CusAnnotationView.h"
#import "CustomCalloutView.h"
#import "SyncManager.h"
#import "LeoMsg.h"
#import <SDWebImage/UIImageView+WebCache.h>
#define kWidth  60.f
#define kHeight 80.f

#define kHoriMargin 5.f
#define kVertMargin 5.f

#define kAvatarHoriMargin 7.f
#define kAvatarVertMargin 7.f

#define kPortraitWidth  50.f
#define kPortraitHeight 70.f

#define kAvatarWidth 46.f
#define kAvatarHeight 46.f

#define kCalloutWidth   200.0
#define kCalloutHeight  140.0

#define LOCATION_BATTERY_IMAGE_PREFIX @"location_Battery"
@interface CusAnnotationView ()
@property (nonatomic, strong) UIImageView *portraitImageView;
@property (nonatomic, strong) UIImageView *avatarImageView;

@property (nonatomic, retain) NSString *mMainLabelValue;
@property (nonatomic, retain) NSString *mSubLabelValue;
@property (nonatomic, retain) NSString *mDateLabelValue;
@property (nonatomic) int mBatteryLabelValue;
@property (nonatomic, retain) NSString *mPhoneNumber;

@end

@implementation CusAnnotationView
@synthesize calloutView ;
@synthesize portraitImageView   = _portraitImageView;
@synthesize avatarImageView     = _avatarImageView;

@synthesize mMainLabelValue     = _mMainLabelValue;
@synthesize mSubLabelValue      = _mSubLabelValue;
@synthesize mDateLabelValue     = _mDateLabelValue;
@synthesize mBatteryLabelValue  = _mBatteryLabelValue;
@synthesize mPhoneNumber        = _mPhoneNumber;
/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    // Drawing code
}
*/
#pragma mark - Override
- (NSString *)mainLabelValue
{
    return self.mMainLabelValue;
}

- (void)setMainLabelValue:(NSString *)mainLabelValue
{
    self.mMainLabelValue = mainLabelValue;
}

- (NSString *)subLabelValue
{
    return self.mSubLabelValue;
}

- (void)setSubLabelValue:(NSString *)subLabelValue
{
    self.mSubLabelValue = subLabelValue;
}

- (NSString *)dateLabelValue
{
    return self.mDateLabelValue;
}

- (void)setDateLabelValue:(NSString *)dateLabelValue
{
    self.mDateLabelValue = dateLabelValue;
}

- (int)batteryLabelValue
{
    return self.mBatteryLabelValue;
}

- (void)setBatteryLabelValue:(int)batteryLabelValue
{
    self.mBatteryLabelValue = batteryLabelValue;
}

- (UIImage *)portrait
{
    return self.portraitImageView.image;
}

- (void)setPortrait:(UIImage *)portrait
{
    self.portraitImageView.image = portrait;
}

- (UIImage *)avatar
{
    return self.avatarImageView.image;
}

- (void)setAvatar:(UIImage *)avatar
{
    self.avatarImageView.image = avatar;
}

- (void)setAvatarWithURL:(NSString *)avatarURL
{
    //[_avatarImageView sd_setImageWithURL:[NSURL URLWithString:avatarURL]];
    [_avatarImageView setImage:[UIImage imageNamed:avatarURL]];
}

- (void)setPhoneNumber:(NSString *)phoneNumber
{
    self.mPhoneNumber = phoneNumber;
}

- (NSString *)phoneNumber
{
    return self.mPhoneNumber;
}

- (void)setSelected:(BOOL)selected
{
    [self setSelected:selected animated:NO];
}

- (void)setSelected:(BOOL)selected animated:(BOOL)animated
{
    if (self.selected == selected)
    {
        return;
    }
    
    if (selected)
    {
        if (self.calloutView == nil)
        {
            /* Construct custom callout. */
            self.calloutView = [[CustomCalloutView alloc] initWithFrame:CGRectMake(0, 0, kCalloutWidth, kCalloutHeight)];
            self.calloutView.center = CGPointMake(CGRectGetWidth(self.bounds) / 2.f + self.calloutOffset.x,
                                                  -CGRectGetHeight(self.calloutView.bounds) / 2.f + self.calloutOffset.y);
            UIFont *Midfont = [UIFont fontWithName:@"Arial" size:12.0f];
            UIFont *Smlfont = [UIFont fontWithName:@"Arial" size:10.0f];
            UILabel *mainLabel = [[UILabel alloc]initWithFrame:CGRectMake(8, 4, kCalloutWidth-16, 20)];
            mainLabel.backgroundColor = [UIColor clearColor];
            mainLabel.textColor = [UIColor blackColor];
            mainLabel.font = Midfont;
            if([self isNullValue:self.mainLabelValue]){
                mainLabel.text = @"北京天安门";
            }else{
                mainLabel.text = self.mainLabelValue;
            }
            [self.calloutView addSubview:mainLabel];
            
            UILabel *subLabel = [[UILabel alloc]initWithFrame:CGRectMake(8, 24, kCalloutWidth-16, 30)];
            subLabel.backgroundColor = [UIColor clearColor];
            subLabel.font = Midfont;
            subLabel.textColor = [UIColor colorWithRed:163.0/255 green:163.0/255 blue:163.0/255 alpha:1];
            subLabel.numberOfLines = 0;
            if ([self isNullValue:self.subLabelValue]) {
                subLabel.text = @"北京天安门";
            }else{
                subLabel.text = self.subLabelValue;
            }
            [self.calloutView addSubview:subLabel];
            
            UILabel *dateLabel = [[UILabel alloc]initWithFrame:CGRectMake(8, 54, 70, 20)];
            dateLabel.backgroundColor = [UIColor clearColor];
            dateLabel.font = Smlfont;
            dateLabel.textColor = [UIColor blackColor];
            dateLabel.text = self.dateLabelValue;
            
            [self.calloutView addSubview:dateLabel];
            
            UIImageView *batteryImage = [[UIImageView alloc] initWithFrame:CGRectMake(120, 54, 20, 20)];
            [batteryImage setImage:[UIImage imageNamed:[self convertBatteryToImage:self.batteryLabelValue]]];
            [batteryImage setContentMode:UIViewContentModeCenter];
            [self.calloutView addSubview:batteryImage];
            
            UILabel *batteryLabel = [[UILabel alloc]initWithFrame:CGRectMake(144, 54, 30, 20)];
            batteryLabel.backgroundColor = [UIColor clearColor];
            batteryLabel.font = Smlfont;
            batteryLabel.textColor = [UIColor blackColor];
            batteryLabel.text = [NSString stringWithFormat:@"%d%%",self.batteryLabelValue];
            [self.calloutView addSubview:batteryLabel];
            
            UIButton *buttonCall = [UIButton buttonWithType:UIButtonTypeRoundedRect];
            buttonCall.frame = CGRectMake(6, 78, 58, 58);
            [buttonCall setBackgroundImage:[UIImage imageNamed:@"location_call_button_normal"] forState:UIControlStateNormal];
            [buttonCall setBackgroundImage:[UIImage imageNamed:@"location_call_button_press"] forState:UIControlStateHighlighted];
            [buttonCall addTarget:self action:@selector(call2Watch:) forControlEvents:UIControlEventTouchUpInside];
            [buttonCall setTag:[self.phoneNumber intValue]];
            [self.calloutView addSubview:buttonCall];
            
            UIButton *buttonBlueAccompany = [UIButton buttonWithType:UIButtonTypeRoundedRect];
            buttonBlueAccompany.frame = CGRectMake(70, 78, 58, 58);
            [buttonBlueAccompany setBackgroundImage:[UIImage imageNamed:@"location_blueaccompany_button_normal"] forState:UIControlStateNormal];
            [buttonBlueAccompany setBackgroundImage:[UIImage imageNamed:@"location_blueaccompany_button_press"] forState:UIControlStateHighlighted];
            [buttonBlueAccompany addTarget:self action:@selector(blueAccompany:) forControlEvents:UIControlEventTouchUpInside];
            [self.calloutView addSubview:buttonBlueAccompany];
            
            UIButton *buttonListen = [UIButton buttonWithType:UIButtonTypeRoundedRect];
            buttonListen.frame = CGRectMake(134, 78, 58, 58);
            [buttonListen setBackgroundImage:[UIImage imageNamed:@"location_listen_button_normal"] forState:UIControlStateNormal];
            [buttonListen setBackgroundImage:[UIImage imageNamed:@"location_listen_button_press"] forState:UIControlStateHighlighted];
            [buttonListen addTarget:self action:@selector(remoteListen:) forControlEvents:UIControlEventTouchUpInside];
            [self.calloutView addSubview:buttonListen];
            
        }
        
        [self addSubview:self.calloutView];
        DataManager *dataManager=[[DataManager alloc] init];
        if(dataManager==NULL)
            return;
        User *user=[User sharedSingleton];
        if(user==NULL||user.uid==NULL)
            return;
        Watch *selectWatch=[dataManager getActiveWatch:user.uid];
        if(selectWatch!=NULL&&selectWatch.deviceUid!=NULL&&![selectWatch.deviceUid isEqualToString:self.deviceUid])
        {
            BOOL result=[dataManager updateWatchState:self.deviceUid];
            if(result)
            {
                [[NSNotificationCenter defaultCenter] postNotificationName:CHANGEWATCH object:nil  userInfo:nil];
            }
            
        }
    }
    else
    {
        [self.calloutView removeFromSuperview];
    }
    
    [super setSelected:selected animated:animated];
}

-(void)call2Watch:(id)sender
{
    if(self.phoneNumber==NULL||[self.phoneNumber isEqualToString:@"(null)"]||[self.phoneNumber isEqualToString:@""])
    {
        [LeoMsg showMsg:@"电话号码不合法"];
        return;
    }
    NSString *callString = [[NSString alloc]initWithFormat:@"%@%@", @"tel://", self.phoneNumber];
    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:callString]];
}
-(void)remoteListen:(id)sender
{
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@""
                                                    message:@"确认开启？"
                                                   delegate:self
                                          cancelButtonTitle:@"取消"otherButtonTitles:@"确定",nil];
    [alert show];
    alert=nil;

}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    if(self.deviceUid==NULL)
        return;
    SyncManager *syncManager=[[SyncManager alloc] init];
    if(syncManager==NULL)
        return;
    switch (buttonIndex) {
        case 0:
            
            break;
        case 1:
            [syncManager sendCommand:self.deviceUid type:REMOTE_CARE watchParams:NULL completion:^(SyncResult result, NSDictionary *retValue, NSString *description) {
                if(result==SUCESS)
                {
                    [LeoMsg showMsg:@"远程关怀发送成功"];
                }
                else
                {
                    [Tooler showHttpMsg:result description:description msg:@"远程关怀发送失败"];
                }
            }];
            break;
        default:
            break;
    }
    
}

-(void)blueAccompany:(id)sender
{
    [[NSNotificationCenter defaultCenter] postNotificationName:CALLBLUEACCOMPANYVIEW object:nil  userInfo:nil];
}

-(NSString *)convertBatteryToImage:(int)value{
    if(value == 100){
        return [NSString stringWithFormat:@"%@%d",LOCATION_BATTERY_IMAGE_PREFIX,100];
    }else if(value >= 75 && value < 100){
        return [NSString stringWithFormat:@"%@%d",LOCATION_BATTERY_IMAGE_PREFIX,75];
    }else if(value >= 50 && value < 75){
        return [NSString stringWithFormat:@"%@%d",LOCATION_BATTERY_IMAGE_PREFIX,50];
    }else if(value >= 25 && value < 50){
        return [NSString stringWithFormat:@"%@%d",LOCATION_BATTERY_IMAGE_PREFIX,25];
    }
    return [NSString stringWithFormat:@"%@%d",LOCATION_BATTERY_IMAGE_PREFIX,5];

}

- (BOOL)pointInside:(CGPoint)point withEvent:(UIEvent *)event
{
    BOOL inside = [super pointInside:point withEvent:event];
    /* Points that lie outside the receiver’s bounds are never reported as hits,
     even if they actually lie within one of the receiver’s subviews.
     This can occur if the current view’s clipsToBounds property is set to NO and the affected subview extends beyond the view’s bounds.
     */
    if (!inside && self.selected)
    {
        inside = [self.calloutView pointInside:[self convertPoint:point toView:self.calloutView] withEvent:event];
    }
    
    return inside;
}

#pragma mark - Life Cycle

- (id)initWithAnnotation:(id<MAAnnotation>)annotation reuseIdentifier:(NSString *)reuseIdentifier
{
    self = [super initWithAnnotation:annotation reuseIdentifier:reuseIdentifier];
    
    if (self)
    {
        self.bounds = CGRectMake(0.f, 0.f , kWidth, kHeight);
        self.backgroundColor = [UIColor clearColor];
        
        /* Create portrait image view and add to view hierarchy. */
        self.portraitImageView = [[UIImageView alloc] initWithFrame:CGRectMake(kHoriMargin, kVertMargin, kPortraitWidth, kPortraitHeight)];
        [self addSubview:self.portraitImageView];
        
        self.avatarImageView = [[UIImageView alloc] initWithFrame:CGRectMake(kAvatarHoriMargin, kAvatarVertMargin, kAvatarWidth, kAvatarHeight)];
        [self.avatarImageView.layer setMasksToBounds:YES];
        self.avatarImageView.layer.cornerRadius=self.avatarImageView.bounds.size.width/2;
        self.avatarImageView.clipsToBounds=YES;
        [self addSubview:self.avatarImageView];
        /* Create name label. */
        //        self.nameLabel = [[UILabel alloc] initWithFrame:CGRectMake(kPortraitWidth + kHoriMargin,
        //                                                                   kVertMargin,
        //                                                                   kWidth - kPortraitWidth - kHoriMargin,
        //                                                                   kHeight - 2 * kVertMargin)];
        //        self.nameLabel.backgroundColor  = [UIColor clearColor];
        //        self.nameLabel.textAlignment    = UITextAlignmentCenter;
        //        self.nameLabel.textColor        = [UIColor whiteColor];
        //        self.nameLabel.font             = [UIFont systemFontOfSize:15.f];
        //        [self addSubview:self.nameLabel];
    }
    
    return self;
}

-(BOOL)isNullValue:(NSString *)value{
    if ([@"" isEqualToString:value] || [@"null" isEqualToString:value]
        || [@"(null)" isEqualToString:value] || value == NULL) {
        return YES;
    }
    return NO;
}

@end
